package com.tuo51.evaluate.repositories.evaluatev2;

import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Record;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

@Repository
public interface EvaluateV2RecordRepository extends JpaRepository<EvaluateV2Record, String>, JpaSpecificationExecutor<EvaluateV2Record> {

    //根據id查詢評測報告
    EvaluateV2Record getByIdAndCreateTeacherId(String id, String staffId);

    //根據childrenId查詢評測報告，分頁
    Page findAllByChildrenId(String cid, Pageable pageable);

    //根據childrenIds查詢評測報告，分頁
    List<EvaluateV2Record> findAllByChildrenIdInAndParentGrantedIsTrue(List<String> cids);

    //根據TeacherId查詢評測報告，分頁
    Page findAllByCreateTeacherIdAndFinishedAndDeleted(String tid, Boolean finished, Boolean deleted, Pageable pageable);

    //找到园区某小朋友的最近一个测评报告
    EvaluateV2Record findFirstByChildrenIdAndFinishedIsTrueOrderByCreatedDesc(String cid);

    //找到园区老师给某小朋友的最近一个未完成测评报告
    @Query(value = "select * from tb_evaluate_record r " +
            "where r.childrenId=?1 and r.month = ?2 and r.createTeacherId = ?3 " +  //and r.finished = false
            "order by created desc limit 1", nativeQuery = true)
    EvaluateV2Record findLatestUnfinishedReportByChildrenId(String cid, Integer month, String tid);

    //找到园区老师给某小朋友的最近一个未完成测评报告
    @Query(value = "select * from tb_evaluate_record r " +
            "where r.childrenId is null and childrenName = ?1 and r.createTeacherId = ?2 " +
            "order by created desc limit 1", nativeQuery = true)
    EvaluateV2Record findLatestUnfinishedReportByChildrenName(String cname, String tid);

    List<EvaluateV2Record> findByChildrenIdAndDeletedIsFalseAndFinishedIsTrueOrderByCreatedAsc(String childrenId);
    List<EvaluateV2Record> findByChildrenIdAndDeletedIsFalseAndFinishedIsTrueOrderByCreatedDesc(String childrenId);
    List<EvaluateV2Record> findAllByChildrenIdAndDeletedIsFalseAndFinishedIsTrueOrderByCreated(String childrenId);

    //迁移报告
    @Modifying
    @Query(value = "update tb_evaluate_record r set r.createTeacherId = ?2, r.evaluatingTeacherId = ?2, r.orgId = ?3 where r.createTeacherId = ?1 ", nativeQuery = true)
    void updateAllReportsFromTo(String sourceTeacherId, String targetTeacherId, String tagetOrgId);

    int countAllByCreateTeacherIdInAndCreatedGreaterThanAndFinishedIsTrue(List<String> ids, Date date);

    int countAllByCreateTeacherIdInAndFinishedIsTrue(List<String> ids);
}
